package com.gen.info.generate_cluster_information.service;

import com.gen.info.generate_cluster_information.config.SourceDataSource;
import com.gen.info.generate_cluster_information.mode.ConnectionInfo;
import com.gen.info.generate_cluster_information.mode.OceanBaseClusterInfoDO;
import com.gen.info.generate_cluster_information.mode.RSUnitVO;
import com.gen.info.generate_cluster_information.util.DBUtil;
import com.gen.info.generate_cluster_information.util.OceanBaseSqlObjectGenerateUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.*;
import java.util.Collection;
import java.util.HashMap;
@Service
@Slf4j
public class CreateUnit {
    @Autowired
    private SourceDataSource sourceDataSource;

    public  void createUnitRS(HashMap<String, RSUnitVO> rsUnitVOHashMap){
      log.info("------------开始创建资源规格--------------");
      //构建连接信息
        ConnectionInfo connectionInfo = new ConnectionInfo();
        BeanUtils.copyProperties(sourceDataSource,connectionInfo);
        log.info("连接信息构建完成："+connectionInfo.toString());
      rsUnitVOHashMap.values().forEach(value ->{
         try {
             final Connection connetcion = DBUtil.getConnetcion(connectionInfo);
             final PreparedStatement smt = DBUtil.getPreparedStatement(connetcion,"select name from oceanbase.__all_unit_config where name = ?");
             smt.setString(1,value.getUnitName());
             final ResultSet rs = smt.executeQuery();
             //判断资源单元是否已经存在
             if (!rs.next()) {
                 final Statement stmt = DBUtil.getCreateStatement(connetcion);
                 final String unitSql = OceanBaseSqlObjectGenerateUtil.getUnitSql(value);
                 stmt.executeUpdate(unitSql);
                     log.info("资源规格" + value.getUnitName() + "建立成功！！");
             }else {
                 log.info("资源规格"+value.getUnitName()+"已经被创建！！");
             }
         } catch (SQLException throwables) {
             throwables.printStackTrace();
         }finally {
             DBUtil.closeConnection();
         }
     });

    }
    public  HashMap<String, RSUnitVO> getUnitRS(Collection<OceanBaseClusterInfoDO> oceanBaseClusterInfoDOS){
    //    final ArrayList<RSUnitVO> rsUnitVOS = new ArrayList<>();
        final HashMap<String, RSUnitVO> rSUnitVOHashMap = new HashMap<>();
        int counter = 1;
        for (OceanBaseClusterInfoDO oceanBaseClusterInfoDO : oceanBaseClusterInfoDOS) {
             RSUnitVO rsUnitVO = new RSUnitVO();
             rsUnitVO.setMemory(oceanBaseClusterInfoDO.getMemory());
             rsUnitVO.setCpu(oceanBaseClusterInfoDO.getCpu());
             rsUnitVO.setUnitName("unit_0"+counter);
             rSUnitVOHashMap.put(oceanBaseClusterInfoDO.getTenant(),rsUnitVO);
             counter++;
        }
        return rSUnitVOHashMap;
    }
}
